<template>
  <Header/>
  <div class="goods" id="goods" name="goods">
    <!-- 面包屑 -->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
        <el-breadcrumb-item>全部商品</el-breadcrumb-item>
        <el-breadcrumb-item v-if="search">搜索</el-breadcrumb-item>
        <el-breadcrumb-item v-else>分类</el-breadcrumb-item>
        <el-breadcrumb-item v-if="search">{{ search }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 面包屑END -->
    <!-- 分类标签 -->
    <div class="nav">
      <div class="product-nav">
        <div class="title">分类</div>
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane
              v-for="item in categoryList"
              :key="item.category_id"
              :label="item.category_name"
              :name="''+item.category_id"
          />
        </el-tabs>
      </div>
    </div>
    <!-- 分类区 -->

    <!-- 主要内容区 -->
    <div class="main">
      <div class="list">
        <MyList :list="product" v-if="product.length>0"></MyList>
        <div v-else class="none-product">抱歉没有找到相关的商品，请看看其他的商品</div>
      </div>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            background
            layout="prev, pager, next"
            :page-size="pageSize"
            :total="total"
            @current-change="currentChange"
        ></el-pagination>
      </div>
      <!-- 分页END -->
    </div>
    <!-- 主要内容区END -->
  </div>

</template>

<script>
import MyList from "@/components/MyList";
import router from "@/router";
import Header from "@/components/Header";
import {useRoute} from "vue-router/dist/vue-router";


export default {
  components: {
    MyList, Header
  },
  setup() {
    const route = useRoute()
    return {
      route
    }
  },
  data() {
    return {
      categoryList: "",//分类列表
      categoryID: [],//分类id
      product: "",//商品列表
      productList: "",
      pageSize: 15,//每页显示的商品数量
      currentPage: 1,//当前页
      total: 0,//商品总数
      activeName: -1,//当前选中的分类
      search: "",//搜索的关键字
    }
  },
  async activated() {
    await this.getCategoryList();//获取分类列表
    this.activeName = -1;// 初始化
    this.total = 0;
    this.currentPage = 1;

    //  判断路由是否传递参数
    if (Object.keys(this.route.query).length === 0) {
      this.categoryID = [0];
      this.activeName = 0;
      return
    }

    //  获取路由参数 -- 传递分类
    if (this.route.query.categoryID !== [] && this.route.query.categoryID !== undefined) {
      this.categoryID = this.route.query.categoryID;
      if (this.categoryID.length === 1) {
        this.activeName = this.categoryID[0]
      }
      return
    }
    //  获取路由参数 -- 传递搜索
    if (this.route.query.search !== "" && this.route.query.search !== undefined) {
      this.search = this.route.query.search;
    }
  },
  watch: {
    // 监听点击了哪个标签
    activeName: function (val) {
      if (val > -1)
        this.categoryID = [Number(val)];

      //  初始化商品页面和当前页码
      this.total = 0;
      this.currentPage = 1;
    },
    search: function (val) {
      if (val.toString() !== "") {
        //  进行搜索
        this.getProductBySearch()
      }
    },
    //  点击分类时清空搜索
    categoryID: function () {
      this.getData()
      this.search = ""
      router.push({
        path: "/goods",
        query: {
          categoryID: this.categoryID,
          search: ""
        }
      });
    },
    //监听路由变化,传递搜索
    route: function (val) {
      if (val.path === '/goods') {
        if (val.query.search !== undefined && val.query.search !== '') {
          this.activeName = -1
          this.currentPage = 1
          this.total = 0
          this.search = val.query.search;
        }
      }
    },
    $route: function (val) {
      if (val.path === '/goods') {
        if (val.query.search !== undefined && val.query.search !== '') {
          this.activeName = -1
          this.currentPage = 1
          this.total = 0
          this.search = val.query.search;
          router.push({
            path: "/goods",
            query: {
              categoryID: [],
              search: this.search
            }
          });
        }
      }
    }

  },
  methods: {
    //  返回顶部
    backTop() {
      const timer = setInterval(() => {
        let top = $(document).scrollTop() || $(document.body).scrollTop();
        let speed = top / 4;
        if (top > 0) {
          $(document).scrollTop(top - speed);
          $(document.body).scrollTop(top - speed);
        } else {
          clearInterval(timer)
        }
      }, 30)
    },
    //页码变化
    currentChange(val) {
      this.currentPage = val;
      if (this.search !== '') {
        this.getProductBySearch()
      } else {
        this.getData()
      }
      this.backTop()
    },
    //  获取分类列表
    async getCategoryList() {
      const url = `${this.$target}/animal/types`;
      await this.$axios.get(url).then(res => {
        const val = {
          category_id: 0,
          category_name: "全部",
        }
        let array = [];
        const cate = res.data.data;
        //  将类型封装
        array.push(val);
        for (let i = 0; i < cate.length; i++) {
          array.push({
            category_id: i + 1,
            category_name: cate[i],
          })
        }
        this.categoryList = array;
      })
          .catch(err => {
            return Promise.reject(err)
          })
    },
    //  获取商品列表
    getData() {
      const url =
          this.categoryID.length === 0 || this.categoryID[0] === 0
              ? `${this.$target}/animal/all` ://   商品分类
              `${this.$target}/animal/find/type/${this.categoryList[this.activeName].category_name}`;
      this.$axios.get(url).then(res => {
        this.product = res.data.data;
        // 取第当前页
        this.product = this.product.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
        // 分页数 向上取整
        this.total = Math.ceil(this.product.length / this.pageSize);
      }).catch(err => {
        return Promise.reject(err)
      })
    },
    //  获取搜索商品列表
    getProductBySearch() {
      const url = `${this.$target}/animal/find/name/${this.search}`;
      this.$axios.get(url).then(res => {
        this.product = res.data.data;
        // 取第当前页
        this.product = this.product.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
        this.total = Math.ceil(this.product.length / this.pageSize);
      }).catch(err => {
        return Promise.reject(err)
      })
    }

  }

}
</script>

<style scoped>
@import "../assets/less/goods.less";
</style>
